package ${package}.${rootArtifactId}.common.util;


import ${package}.${rootArtifactId}.common.exception.BusinessException;

import java.util.concurrent.TimeUnit;

/**
 * 生成SequenceNo=uniqueKey+定长序列（suffixLength=序列长度）
 *
 * @author weidong.lin
 * @date 2021/7/8 11:15
 */
public class SequenceUtil {
    private int timeOut = 2;//单位为天
    private String uniqueKey = null;
    private int suffixLength = 3;

    public SequenceUtil(int timeOut, String uniqueKey, int suffixLength) {
        this.timeOut = timeOut;
        this.uniqueKey = uniqueKey;
        this.suffixLength = suffixLength;
    }

    public static SequenceUtil getInstance(int timeOut, String uniqueKey, int suffixLength) {
        return new SequenceUtil(timeOut, uniqueKey, suffixLength);
    }

    /*
     *获取下一个序号 【自增1】
     */
    public String getNextSequenceNo() {
        if (uniqueKey == null) {
            return "";
        }
        return getSequenceNum(1);
    }

    //获取业务序号
    private String getSequenceNum(int increment) {
        Long incrementResult = RedisUtil.incrBy(uniqueKey, increment);
        if (incrementResult == null) {
            throw new BusinessException("生成sequence失败");
        }
        if (incrementResult == increment) {
            RedisUtil.expire(uniqueKey, this.timeOut, TimeUnit.DAYS);
        }
        return appendZero(incrementResult, suffixLength);

    }

    //长度不足补0
    private String appendZero(Long num, int length) {
        StringBuilder str = new StringBuilder(uniqueKey);
        for (int i = String.valueOf(num).length(); i < length; i++) {
            str.append(0);
        }
        str.append(num);
        return str.toString();
    }
}
